package com.kye.express.business.order.scan_code_address;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.kye.addrpicker.AddressPickerActivity;
import com.kye.addrpicker.model.AddressPickerResult;
import com.kye.base.DebounceObservableTransformer;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatActivity;
import com.kye.express.business.order.scan_code_addresses.ScanCodeAddressListActivity;
import com.kye.express.databinding.ActivityScanCodeAddressEditBinding;
import com.kye.express.utils.ToolbarManager;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.model.bean.order.scan_code_order.ScanCodeOrderAddress;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function4;

public class ScanCodeAddressEditActivity extends BaseAppCompatActivity implements ScanCodeAddressEditContract.ScanCodeAddressEditView {

    public static final String KEY_ADDRESS = ScanCodeAddressListActivity.KEY_ADDRESS;

    public static final String KEY_ADDRESS_TYPE = ScanCodeAddressListActivity.KEY_ADDRESS_TYPE;

    public static final String SEND_ADDRESS = ScanCodeAddressListActivity.SEND_ADDRESS;
    public static final String RECEIVE_ADDRESS = ScanCodeAddressListActivity.RECEIVE_ADDRESS;

    private ActivityScanCodeAddressEditBinding mBinding;
    private ScanCodeAddressEditContract.ScanCodeAddressEditPresenter mPresenter;
    private Dialog mDialog;

    public static void startActivityForResult(Activity activity, ScanCodeOrderAddress addressData, String addressType, int requestCode) {
        activity.startActivityForResult(
                new Intent(activity, ScanCodeAddressEditActivity.class)
                        .putExtra(KEY_ADDRESS, addressData)
                        .putExtra(KEY_ADDRESS_TYPE, addressType),
                requestCode
        );
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_scan_code_address_edit);
        initEvent();
        initData();
    }

    private void initEvent() {
        ToolbarManager.setToolbar(this, mBinding.toolbar);

        RxView.clicks(mBinding.linearLayoutAddress)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        AddressPickerActivity.startActivityForResult(ScanCodeAddressEditActivity.this, "选择地址", AddressPickerActivity.Levels.area);
                    }
                });

        Observable.combineLatest(
                RxTextView.textChanges(mBinding.editTextPerson),
                RxTextView.textChanges(mBinding.editTextPhone),
                RxTextView.textChanges(mBinding.textViewAddress),
                RxTextView.textChanges(mBinding.editTextDetailAddress),
                new Function4<CharSequence, CharSequence, CharSequence, CharSequence, Boolean>() {
                    @Override
                    public Boolean apply(CharSequence charSequence, CharSequence charSequence2, CharSequence charSequence3, CharSequence charSequence4) throws Exception {
                        return
                                !TextUtils.isEmpty(charSequence) &&
                                        !TextUtils.isEmpty(charSequence2) &&
                                        !TextUtils.isEmpty(charSequence3) &&
                                        !TextUtils.isEmpty(charSequence4);
                    }
                }
        )
                .compose(bindToLifecycle())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        mBinding.buttonConfirm.setEnabled(aBoolean);
                    }
                });

        RxView.clicks(mBinding.buttonConfirm)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mPresenter.submit(
                                mBinding.getProvince(),
                                mBinding.getCity(),
                                mBinding.getCounty(),
                                mBinding.editTextDetailAddress.getText().toString().trim(),
                                mBinding.editTextPerson.getText().toString().trim(),
                                mBinding.editTextPhone.getText().toString().trim(),
                                mBinding.switchDefault.isChecked(),
                                mBinding.getSendAddress(),
                                mBinding.switchSave.isChecked(),
                                mBinding.getAddress() != null ? mBinding.getAddress().getGuid() : null
                        );
                    }
                });
    }

    private void initData() {
        mBinding.setSendAddress(SEND_ADDRESS.equals(getIntent().getStringExtra(KEY_ADDRESS_TYPE)));
        setTitle(mBinding.getSendAddress() ? " 寄件地址" : "收件地址");
        ScanCodeOrderAddress address = (ScanCodeOrderAddress) getIntent().getSerializableExtra(KEY_ADDRESS);
        mBinding.setAddress(address);

        if (address != null) {
            mBinding.setProvince(address.getProvince());
            mBinding.setCity(address.getCity());
            mBinding.setCounty(address.getArea());
        }

        mPresenter = new ScanCodeAddressEditContract.ScanCodeAddressEditPresenter();
        mPresenter.bind(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AddressPickerActivity.ADDRESS_PICKER_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            AddressPickerResult resultAddress = (AddressPickerResult) data.getSerializableExtra(AddressPickerActivity.KEY_ARG_PICKED_RESULT);
            mBinding.setProvince(resultAddress.getProvince());
            mBinding.setCity(resultAddress.getCity());
            mBinding.setCounty(resultAddress.getArea());
        }
    }

    @Override
    public void onResult(ScanCodeOrderAddress address) {
        setResult(RESULT_OK, new Intent().putExtra(KEY_ADDRESS, address));
        finish();
    }

    @Override
    public void onError() {
        ToastManager.show(this, R.string.common_net_error);
    }

    @Override
    public void onError(String msg) {
        ToastManager.show(this, msg);
    }

    @Override
    public void onLoading() {
        mDialog = KyeProgressDialog.show(this, mDialog);
    }

    @Override
    public void onLoaded() {
        KyeProgressDialog.dismiss(mDialog);
    }
}
